import React, {Component} from 'react';
import {
  View,
  Text,
  TextInput,
  Alert,
  StyleSheet,
  ScrollView,
  StatusBar,
  TouchableOpacity,
  ActivityIndicator,
  Image,
  ToastAndroid,
} from 'react-native';
import RNFileSelector from 'react-native-file-selector';
import {getData} from '../../../storage';
export default class FileSelectorTest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filePath: '',
    };
  }

  selectFile() {
    console.log('begin select files');
    RNFileSelector.Show({
      title: 'Select File',
      onDone: path => {
        console.log('file selected: ' + path);
        this.setState({
          filePath: 'file://' + path,
        });
      },
      onCancel: () => {
        console.log('cancelled');
      },
    });
  }

  async upLoadFile(filePath) {
    let token = '';
    await getData('token', function(text) {
      token = text;
    });
    let formData = new FormData();
    let fileName = filePath.substr(filePath.lastIndexOf('/') + 1);
    console.log('fileName: ' + fileName);
    formData.append('files', {
      uri: this.state.filePath,
      type: 'multipart/form-data',
      name: fileName,
    });
    formData.append('title', 'mgl 发起的提案');
    formData.append('proposalTitle', 'mgl 发起的提案');
    formData.append('proposalLimit', 3);
    formData.append('acceptorId', 167334);
    ToastAndroid.showWithGravity('uploading', 1, ToastAndroid.CENTER);
    return fetch('http://47.104.75.42:9000/api/proposal/createProposal.shtml', {
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data',
        imei: 1,
        version: 2,
        token: token,
      },
      body: formData,
    })
      .then(response => {
        console.log(response.toString());
        return response.json();
      })
      .then(responseJson => {
        ToastAndroid.showWithGravity('success', 1, ToastAndroid.BOTTOM);
        console.log(responseJson.error_code);
        alert(responseJson.error_code);
        // console.log(responseJson);
      })
      .catch(e => {
        console.log('error:' + e);
      });
  }
  render() {
    return (
      <View>
        <View style={{alignSelf: 'center', marginTop: 80}}>
          <Text>选择的文件路径为： {this.state.filePath}</Text>
        </View>
        <TouchableOpacity
          style={{alignSelf: 'center', marginTop: 100, borderWidth: 2}}
          onPress={() => {
            this.selectFile();
          }}>
          <Text>从本地选择文件</Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={{alignSelf: 'center', marginTop: 50, borderWidth: 2}}
          onPress={() => {
            this.upLoadFile(this.state.filePath);
          }}>
          <Text>确认上传</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
